/* 
 * File:   Utils.h
 * Author: Sergey Karakovskiy
 *
 * Created on February 19, 2010, 5:00 PM
 */

#ifndef _UTILS_H
#define	_UTILS_H
#include <jni.h>

template <typename T> PyObject* convertJavaArrayToPythonTuple(JNIEnv *env, T arr)
{
    jsize len = env->GetArrayLength(arr);
    jint* obs = (jint*)env->GetPrimitiveArrayCritical(arr, NULL);
    PyObject* items = PyTuple_New(len);
    for (jsize i = 0; i < len; ++i)
        PyTuple_SET_ITEM(items, (Py_ssize_t)i, PyInt_FromLong(obs[(Py_ssize_t)i]));
    env->ReleasePrimitiveArrayCritical(arr, obs, 0);
    return items;
}

template <> PyObject* convertJavaArrayToPythonTuple<jfloatArray>(JNIEnv *env, jfloatArray arr)
{
    jsize len = env->GetArrayLength(arr);
    jfloat* obs = (jfloat*)env->GetPrimitiveArrayCritical(arr, NULL);
    PyObject* items = PyTuple_New(len);
    for (jsize i = 0; i < len; ++i)
        PyTuple_SET_ITEM(items, (Py_ssize_t)i, PyFloat_FromDouble(obs[(Py_ssize_t)i]));
    env->ReleasePrimitiveArrayCritical(arr, obs, 0);
    return items;
}

jintArray convertPythonTupleTojintArray(JNIEnv *env, PyObject* tuple)
{
    if (tuple == NULL)
    {
        std::cout << "\ntuple is NULL\n"; std::cout.flush();
        return NULL;
    }
    // convert back to Java compatible data format
//    std::cout << "\nC++: here we go4!\n"; std::cout.flush();
    int actionSize = PyTuple_Size(tuple);
//    std::cout << "C++: here we go5!\n"; std::cout.flush();
    jintArray ret = env->NewIntArray(actionSize);
//    (*env)->SetByteArrayRegion(env, jb, 0, 5, (jbyte *)m);
    jint* buff = new jint[actionSize];
    for (int i = 0; i < actionSize; i++)
        buff[i] = (jint) PyInt_AsLong(PyTuple_GetItem(tuple, i));

    env->SetIntArrayRegion((jintArray)ret, 0, actionSize, (jint*)buff);
    return ret;
}



#endif	/* _UTILS_H */

